<template>
  <div>
    <!-- 三级联动的组件 -->
    <Category :disabled="!isShowList" />
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      :style="{ marginTop: '40px' }"
    >
      <template #header v-if="isShowList">
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          @click="addAttr"
          :disabled="!category3Id"
          >添加属性</el-button
        >
      </template>
      <el-table border stripe :data="attrList" v-if="isShowList">
        <el-table-column type="index" width="80" label="序号" align="center" />
        <el-table-column
          width="150"
          label="属性名称"
          prop="attrName"
          align="center"
        />
        <el-table-column label="属性值名称列表" prop="attrValueList">
          <!-- 通过作用域插槽将数据接收，然后拿到当前的数据遍历生成tag -->
          <template #default="{ row }">
            <el-tag
              :style="{ marginRight: '10px' }"
              :type="tagColor()"
              size="small"
              v-for="item in row.attrValueList"
              :key="item.id"
              >{{ item.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column width="150" label="操作" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="default"
              @click="editAttrValue(row)"
              :icon="Edit"
            />
            <el-popconfirm title="确定删除吗" @confirm="deleteAttr(row.id)">
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  @click=""
                  :icon="Delete"
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div v-else>
        <el-form label-width="80px" :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名"
              v-model="newAttrData.attrName"
            />
          </el-form-item>
        </el-form>
        <div>
          <el-button
            type="primary"
            @click="addAttrValue"
            :icon="Plus"
            :disabled="!newAttrData.attrName"
            >添加属性值</el-button
          >
          <el-button type="default" @click="cancel">取消</el-button>
        </div>
        <el-table
          :data="newAttrData.attrValueList"
          border
          stripe
          :style="{ marginTop: '20px' }"
        >
          <el-table-column
            type="index"
            width="80"
            label="序号"
            align="center"
          />
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <div @click="changeToEdit(row)">
                <el-input
                  ref="editEle"
                  placeholder="请输入新的属性值"
                  size="small"
                  v-model="row.valueName"
                  v-if="row.isEdit"
                  @blur="saveEditLook(row, $index)"
                />
                <span v-else>{{ row.valueName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="{ $index }">
              <el-popconfirm
                title="确定删除吗"
                @confirm="delateAttrValue($index)"
              >
                <template #reference>
                  <el-button type="danger" size="default" :icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 30px">
          <el-button
            type="primary"
            @click="saveAttr"
            :disabled="!newAttrData.attrValueList.length"
            >保存</el-button
          >
          <el-button type="default" @click="cancel">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { watch, ref, nextTick } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import useAttrStore from "@/stores/attr";
import {
  requestAddOrUpdateAttr,
  requestAttrList,
  requestDeleteAttr,
  type attrListItemType,
  type attrValueListItemType,
  type attrValueListType,
  type attrListType
} from "@/api/Attr";
import cloneDeep from "lodash/cloneDeep";
//获取attr的store实例
const attrStore = useAttrStore();

//将需要用来请求的id解构
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore);

/**@attrList 初始化创建一个属性列表*/
const attrList = ref<attrListType>([]);

/**@getAttrList 获取属性列表的事件*/
const getAttrList = async () => {
  const result = await requestAttrList({
    category1Id: category1Id.value as number,
    category2Id: category2Id.value as number,
    category3Id: category3Id.value as number,
  });
  //将请求回来的数据给到attrList
  attrList.value = result;
};

//监听三级列表的改动，请求属性列表的数据，开启立即监听，使其在切换路由的时候也会默认执行一次
watch(
  category3Id,
  (newVal) => {
    //初始化没数据的时候，如果category3Id没有数据则不发送请求
    if (!newVal) return;
    getAttrList();
  },
  //开启立即监听
  { immediate: true }
);

//tag随机颜色
const tagColor = () => {
  return ["", "success", "warning", "info", "danger"][
    ~~(Math.random() * 5)
  ] as any;
};

//新增或修改属性的数据
const newAttrData = ref<attrListItemType>({
  attrName: "",
  categoryId: category3Id.value as number, //固定是category3Id
  categoryLevel: 3, //固定是等级三
  attrValueList: [],
});

/**@isShowList 创建一个列表与新增的开关的变量*/
const isShowList = ref(true);

/**@addAttr 点击添加按钮切换到添加修改组件*/
const addAttr = () => {
  //切换到新增
  isShowList.value = false;
  //每次新增初始化数据
  newAttrData.value = {
    attrName: "",
    categoryId: category3Id.value as number, //固定是category3Id
    categoryLevel: 3, //固定是等级三
    attrValueList: [],
  };
};
/**@cancel 点击取消回到属性列表组件*/
const cancel = () => {
  isShowList.value = true;
};
/**@oldAttrData 初始化一个属性值列表，用来来提交的时候做判断 */
let oldAttrData: attrValueListType | null = null;
/**@editAttrValue 修改属性值的事件 */
const editAttrValue = (row: attrListItemType) => {
  isShowList.value = false;
  row.attrValueList.forEach((item) => (item.isEdit = false));
  //回填的时候，深拷贝，因为数据里有数组
  newAttrData.value = cloneDeep(row);
  oldAttrData = row.attrValueList;
};

//获取编辑表单的实例
const editEle = ref();
/**@oldAttrValueName 保存旧值的容器，有值表示为修改，没值则是新增*/
let oldAttrValueName = "";
/**@addAttrValue 添加属性值的事件*/
const addAttrValue = () => {
  const newAttrValue = ref<attrValueListItemType>({
    valueName: "", //这里是属性值
    attrId: newAttrData.value.id, //无论新增还是修改这个属性都是存在的，等修改的时候就自然有id了，新增没有就没有
    isEdit: true,
  });
  //将新的属性值插入attrValueList中
  newAttrData.value.attrValueList.push(newAttrValue.value);
  //新添加的表单自动获取焦点
  nextTick(() => {
    editEle.value.focus();
  });
};

/**@changeToEdit 将属性改为编辑模式 */
const changeToEdit = (row: attrValueListItemType) => {
  oldAttrValueName = row.valueName;
  row.isEdit = true;
  nextTick(() => {
    editEle.value.focus();
  });
};

/**@saveEditLook 保存编辑*/
const saveEditLook = (row: attrValueListItemType, $index: number) => {
  row.isEdit = false;
  //判断编辑输入框没有内容
  if (!row.valueName.trim()) {
    //旧的值没有字段的时候，表示是新增的数据为空
    if (!oldAttrValueName) {
      //如果只是针对最后一条数据使用pop也挺好的
      // newAttrData.value.attrValueList.pop()
      //如果是不确定位置的属性，用splice更精准
      newAttrData.value.attrValueList.splice($index, 1);
      //旧值有内容表示是修改值为空
    } else {
      row.valueName = oldAttrValueName;
    }
  }
  //输入框是有内容的判断
  const isReset = newAttrData.value.attrValueList.some((item) => {
    if (row === item) {
      return;
    }
    return item.valueName === row.valueName;
  });
  //判断除了自己添加的以外的值是否有相同的，如果有就把当前这项删掉
  if (isReset) {
    //依然通过判断旧值确认当前是编辑还是新增
    if (!oldAttrValueName) {
      newAttrData.value.attrValueList.splice($index, 1);
    } else {
      row.valueName = oldAttrValueName;
    }
  }
  //无论执行如何都把旧值清空，以免影响新增的判断
  oldAttrValueName = "";
};

/**@saveAttr 保存属性的逻辑*/
const saveAttr = async () => {
  //遍历属性值列表将isEdit编辑删除
  newAttrData.value.attrValueList.forEach((item) => {
    delete item.isEdit;
  });
  //判断属性值是否有数据，如果没有则直接结束
  if (!newAttrData.value.attrValueList.length) {
    return ElMessage.error("属性值不能为空");
  }
  //判断当前数据与初始是否一致，如果一致则结束
  const isSame = newAttrData.value.attrValueList.every((item1) => {
    //判断是否是新增,如果是新增是没有旧的attr的
    if (!oldAttrData) return;
    if (oldAttrData.length === newAttrData.value.attrValueList.length) {
      return oldAttrData.some((item2: attrValueListItemType) => {
        return item1.valueName === item2.valueName;
      });
    }
  });
  if (isSame) {
    return ElMessage.error("属性值没有改变，请重新输入");
  }
  //保存的请求
  try {
    await requestAddOrUpdateAttr(newAttrData.value);
    getAttrList();
    ElMessage.success("保存属性成功");
    isShowList.value = true;
  } catch (e) {
    ElMessage.error("保存属性失败");
  }
};
/**@delateAttrValue 删除属性值 */
const delateAttrValue = ($index: number) => {
  newAttrData.value.attrValueList.splice($index, 1);
};
/**@deleteAttr 删除属性 */
const deleteAttr = async (id: number) => {
  try {
    await requestDeleteAttr(id);
    ElMessage.success("删除属性成功");
    getAttrList();
  } catch (e) {
    ElMessage.error("删除属性失败");
  }
};
</script>
